package com.panda.web.utils.DeepSeek;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class JsonToMapConverter {

    /**
     * 将 JSON 数据扁平化为 Map
     *
     * @param jsonString JSON 字符串
     * @return 扁平化的 Map
     * @throws IOException JSON 解析异常
     */
    public static Map<String, String> convertJsonToMap(String jsonString) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(jsonString);
        Map<String, String> dataMap = new HashMap<>();
        flattenJson("", rootNode, dataMap);
        return dataMap;
    }

    /**
     * 递归扁平化 JSON 数据
     *
     * @param prefix 前缀（用于嵌套字段）
     * @param node   JSON 节点
     * @param map    存储结果的 Map
     */
    private static void flattenJson(String prefix, JsonNode node, Map<String, String> map) {
        if (node.isObject()) {
            Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
            while (fields.hasNext()) {
                Map.Entry<String, JsonNode> field = fields.next();
                flattenJson(prefix.isEmpty() ? field.getKey() : prefix + "." + field.getKey(), field.getValue(), map);
            }
        } else if (node.isArray()) {
            for (int i = 0; i < node.size(); i++) {
                flattenJson(prefix + "[" + i + "]", node.get(i), map);
            }
        } else {
            map.put(prefix, node.asText());
        }
    }
}